package com.hgk.common.common.ui.activity;


import android.annotation.SuppressLint;
import android.content.ContentUris;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.provider.DocumentsContract;
import android.provider.MediaStore;
import android.view.MenuItem;

import com.common.dongqiuhui.apps.comm.tools.BallUtil;
import com.common.dongqiuhui.apps.comm.tools.FileUtil;
import com.common.dongqiuhui.apps.comm.tools.FolderOper;
import com.common.dongqiuhui.apps.comm.util.ParseUtil;
import com.common.nostra13.universalimageloader.utils.StorageUtils;
import com.hgk.common.common.util.LoadImageDisplayOption;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;

/**
 * 拍照activity
 * fyh
 */
public abstract class BallPhotoToolActivity extends BallTitleAcitivty {

	/**
	 * 相机 
	 */
	public final int PHOTO_CAMERA = 2;
	/**
	 * 相册
	 */
	public final int PHOTO_ALBUM = 1;

	/**
	 * 系统相册activity request id 3001
	 */
	private static final int REQUEST_PHOTO_LIBRARY = 3001;

	/**
	 * 手机拍照activity request id 3000;
	 */
	public static final int CAMERA_WITH_DATA = 3000;

	/**
	 * 旋转图片activity request id 3002
	 */
	private static final int REQUEST_PHOTO_CHANGE = 3002;
	
	/**
	 * 选多图activity request id 3002
	 */
	private static final int REQUEST_MORE_PHOTO = 3003;

	/**
	 * 图片文件
	 */
	private File mImageFile;
	/**
	 * 图片缓存
	 */
	private Bitmap mBitmap;
	
//	/**
//	 * 图片缓存数组
//	 */
//	private List<Bitmap> mBitmaps;
	

	/**
	 * 图片宽度
	 */
	private int mBitmapW=1024;
	/**
	 * 图片高度
	 */
	private int mBitmapH=768;

	/**
	 * 图片质量,默认是80,最大值100
	 */
	private int quality = 80;

	/**
	 * 图片缓存成功
	 */
	private final int CACHE_SUCCESS = 0;
	/**
	 * 图片缓存成功
	 */
	private final int CACHE_SUCCESS_MORE = 3;
     /**
      * type头像还是头像背景的截取框大小
      */
	private String type="0";
	/**
	 * 图片缓存失败
	 */
	private final int CACHE_FAIL = 1;
	private static final int CAMERA_SUCCESS = 101;
	
	private String takePhotoFileName="takePhoto.jpg";
	private String choosePhotoFileName="choosePhoto.jpg";
	/**
	 * 剪切后的文件路径
	 */
	private String tempPath="";
	/**
	 * 剪切后的文件路径数组
	 */
	private String[] tempPaths;
	/**
	 * 是否剪切的标识 0不剪切1剪切
	 */
	private String cropFlag="0";
	private Bitmap tmpBitmap=null;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
	}

	@Override
	public boolean onContextItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case PHOTO_ALBUM:
			// 系统相册
			selectPhoto();
			break;
		case PHOTO_CAMERA:
			// 手机拍照
			takePhoto();
			break;
		default:
			break;
		}

		return false;
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
        /** 使用SSO授权必须添加如下代码 */
        // SSO 授权回调
        // 重要：发起 SSO 登陆的 Activity 必须重写 onActivityResult
//        if (mSsoHandler != null && data != null) {
//            mSsoHandler.authorizeCallBack(requestCode, resultCode, data);
//        }

		if(data==null){
			Message msg = new Message();
			msg.what = CACHE_FAIL;
			photoHandler.sendMessage(msg);
		}
		switch (requestCode) {
		case REQUEST_PHOTO_LIBRARY:
			// 系统相册
			if (resultCode == RESULT_CANCELED) {
				break;
			}
			try {
				Uri uri = data.getData();
				setImageForUri(uri);
				Intent i = new Intent();
				i.putExtra("img_url", mImageFile.getPath());
				i.putExtra("img_w", mBitmapW);
				i.putExtra("img_h", mBitmapH);
				i.putExtra("type", this.type);
//				if(cropFlag.equalsIgnoreCase("1")){
//					i.setClass(getApplicationContext(), BabytreeCropModifyActivity.class);
//				}else{
//					//i.setClass(getApplicationContext(), BabytreeModifyActivity.class);
//					i.setClass(getApplicationContext(), BabytreeSelectImageCropActivity.class);
//				}
				//i.setClass(getApplicationContext(), BabytreeSelectImageCropActivity.class);
				//startActivityForResult(i, REQUEST_PHOTO_CHANGE);
			} catch (Exception e) {
			}

			break;
		case REQUEST_PHOTO_CHANGE:
			// 旋转图片
			if (data != null) {
				tempPath=data.getStringExtra("tempPath");
				if(isMorePhoto){
					Message msg = new Message();
					msg.what = CACHE_SUCCESS;
					photoHandler.sendMessage(msg);
				}else{
					setBitmap(tempPath);
				}
			} else {
				Message msg = new Message();
				msg.what = CACHE_FAIL;
				photoHandler.sendMessage(msg);
			}
			break;
		case CAMERA_WITH_DATA:
			// 系统拍照
			if (resultCode == RESULT_CANCELED) {
				break;
			}
			try {
				Intent i2 = new Intent();
				if(mImageFile!=null){
				i2.putExtra("img_url", mImageFile.getPath());
				}else{
					break;
				}
				i2.putExtra("img_w", mBitmapW);
				i2.putExtra("img_h", mBitmapH);
				i2.putExtra("type", this.type);
				//i2.setClass(getApplicationContext(), BabytreeSelectImageCropActivity.class);
				startActivityForResult(i2, REQUEST_PHOTO_CHANGE);
			} catch (Exception e) {
				e.printStackTrace();
				Message msg = new Message();
				msg.what = CACHE_FAIL;
				photoHandler.sendMessage(msg);
			}

			break;
		default:
			break;
		}

	}

	/**
	 * 获取缓存图片
	 */
	protected abstract void getBitmap(Bitmap bitmap,String path);

	private void setImageForUriOld(Uri uri) {
		File fromFile = null;
		if (uri.toString().toLowerCase(Locale.getDefault()).startsWith("file://")) {
			fromFile = new File(uri.toString().substring(7));
		} else {
			String[] proj = { MediaStore.Images.Media.DATA };
			Cursor cursor = managedQuery(uri, proj, null, null, null);
			int actual = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
			cursor.moveToFirst();
			String filePath = cursor.getString(actual);
			fromFile = new File(filePath);
		}
		if (FolderOper.isExistSdcard(this)) {
			File toFile = new File(StorageUtils.getCacheDirectory(this), choosePhotoFileName);
			BallUtil.copyFile(fromFile, toFile, true);
			mImageFile = toFile;
		}
	}
	private void setImageForUri(Uri uri) {
		File fromFile = null;
		if (uri.toString().toLowerCase(Locale.getDefault()).startsWith("file://")) {
			fromFile = new File(uri.toString().substring(7));
		}
	else {
		  String picturePath=getPath(mContext, uri);
		  fromFile = new File(picturePath);
		}
		if (FileUtil.isExistSdcard(this)) {
			File toFile = new File(LoadImageDisplayOption.getCacheDirectory(this), choosePhotoFileName);
			FileUtil.copyFile(fromFile, toFile, true);
			mImageFile = toFile;
		}
	}
	/**
	 * 显示view
	 * fyh
	 * @param w
	 *            最终需求图片宽度
	 * @param h
	 *            最终需求图片高度
	 *            type 1头像框2头像背景框
	 */
	protected void showPhotoMenu(String title,int w, int h,String cropFlag,String type) {
		// view.showContextMenu();
		this.cropFlag=cropFlag;
		this.type=type;
		String[] str = { "手机相册", "系统拍照", "取消" };
		showAlertItemDialog(title, str, new DialogInterface.OnClickListener() {
			@Override
			public void onClick(DialogInterface dialog, int which) {
				switch (which) {
				case 0:
					// 系统相册
					selectPhoto();
					break;
				case 1:
					// 手机拍照
					takePhoto();
					break;
				case 2:

					break;
				default:
					break;
				}
				closeDialog();
			}
		});
		this.mBitmapW = w;
		this.mBitmapH = h;
	}
	
	public String getPhotoPath() {
		return mImageFile == null ? null : mImageFile.getPath();
	}
	
	protected void showPhotoMenu(int w, int h,String cropFlag,String type) {
		showPhotoMenu("",w, h, cropFlag, type);
	}
	protected void setType_Size(int w,int h,String cropFlag,String type){
		this.mBitmapW=w;
		this.mBitmapH=h;
		this.cropFlag=cropFlag;
		this.type = type;
	}
	private boolean isMorePhoto=false;
	private int picNum=0;
	protected void setIsMorePhoto(boolean ismore,int mNum){
		this.isMorePhoto=ismore;
		this.picNum=mNum;
	}

	protected void showPhotoMenu(int w, int h, String []other,String cropFlag) {
	 	  this.cropFlag=cropFlag;
	      String[] str1 = { "手机相册", "系统拍照"};
		  String[] str = new String[3 + other.length];
          String[] end={"取消"};
		  for (int j = 0; j < str1.length; ++j) {
		   str[j] = str1[j];
		  }

		  for (int j = 0; j < other.length; ++j) {
		   str[str1.length + j] = other[j];
		  }
		  str[str.length-1]="取消";
		 // str[str.length+str1.length]=end[0];

	showAlertItemDialog("", str, new DialogInterface.OnClickListener() {
		@Override
		public void onClick(DialogInterface dialog, int which) {
			switch (which) {
			case 0:
				// 系统相册
				selectPhoto();
				break;
			case 1:
				// 手机拍照
				takePhoto();
				break;
			case 2:
				otherdoing();
				break;
			default:
				break;
			}
			closeDialog();
		}
	});
	this.mBitmapW = w;
	this.mBitmapH = h;
	}

//	protected void showPhotoMenu(int w, int h, String other, String url) {
//		// view.showContextMenu();
//		String[] str = { "手机相册", "系统拍照", other, "取消" };
//
//		showAlertItemDialog("", str, new DialogInterface.OnClickListener() {
//			@Override
//			public void onClick(DialogInterface dialog, int which) {
//				switch (which) {
//				case 0:
//					// 系统相册
//					selectPhoto();
//					break;
//				case 1:
//					// 手机拍照
//					takePhoto();
//					break;
//				case 2:
//					otherdoing();
//					break;
//				default:
//					break;
//				}
//				closeDialog();
//			}
//		});
//		this.mBitmapW = w;
//		this.mBitmapH = h;
//		this.mBitmapPath = url;
//	}

	/**
	 * 弹出窗口其他选项 暂时这么写 以后要换成list
	 */
	public void otherdoing() {

	}

	/**
	 * 系统相册
	 */
	protected void selectPhoto() {
			try{
			Intent intent=new Intent(Intent.ACTION_GET_CONTENT);//ACTION_OPEN_DOCUMENT
			intent.addCategory(Intent.CATEGORY_OPENABLE);
			intent.setType("image/*");
			startActivityForResult(intent, REQUEST_PHOTO_LIBRARY);
			}catch(Exception e){
				e.printStackTrace();
			}
	}

	/**
	 * 手机拍照
	 */
	protected void takePhoto() {
		if (FolderOper.isExistSdcard(this)) {
			mImageFile = new File(StorageUtils.getCacheDirectory(this),takePhotoFileName);
			Intent intent = getTakePickIntent(mImageFile);
			startActivityForResult(intent, CAMERA_WITH_DATA);
		}
	}

	private Intent getTakePickIntent(File f) {
		Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
		intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(f));
		return intent;
	}

	

	@Override
	protected void onDestroy() {
		super.onDestroy();
		if (mImageFile != null) {
			mImageFile.deleteOnExit();
			mImageFile = null;
		}
		try {
			if (mBitmap != null) {
				mBitmap.recycle();
				mBitmap = null;
			}
			if (tmpBitmap != null) {
				tmpBitmap.recycle();
				tmpBitmap = null;
			}
		} catch (Exception e) {
			e.printStackTrace();
		}

	}

	/**
	 * 设置bitmap
	 * 
	 * @param s
	 *            路径
	 * @param
	 */
	private void setBitmap(String s) {
		Message msg = new Message();
		BitmapFactory.Options opts = new BitmapFactory.Options();
		opts.inJustDecodeBounds = true;
		// dada add 先导入缩放并导入内存
		opts.inSampleSize = BallUtil.computeSampleSize(opts, -1, mBitmapW * mBitmapH);
		opts.inJustDecodeBounds = false;
		try {
			mBitmap = BitmapFactory.decodeFile(s, opts);
		} catch (Exception e) {
			e.printStackTrace();
			if (mBitmap != null) {
				mBitmap.recycle();
				mBitmap = null;
			}
			msg.what = CACHE_FAIL;
			photoHandler.sendMessage(msg);
		}
		msg.what = CACHE_SUCCESS;
		photoHandler.sendMessage(msg);
	}

	/**
	 * 读取图片文件名
	 * 
	 * @param date
	 * @return
	 */
	private String getPhotoFilename(Date date) {
		SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMddKms", Locale.CHINA);
		return dateFormat.format(date) + ".jpg";
	}
	/**
	 * 设置图片质量
	 * 
	 * @param quality
	 */
	protected void setQuality(int quality) {
		if (quality >= 80 || quality <= 20) {
			return;
		} else {
			this.quality = quality;
		}
	}

	@SuppressLint("HandlerLeak")
	private Handler photoHandler = new Handler() {
		@Override
		public void handleMessage(Message msg) {

			switch (msg.what) {
			case CACHE_SUCCESS:
				if(mBitmap!=null){
					getBitmap(mBitmap,tempPath);
				}else{
					getBitmap(null,tempPath);
				}
				break;
			case CACHE_SUCCESS_MORE:
				break;
			case CACHE_FAIL:
				break;
			default:
				break;
			}
		}
	};
	@SuppressLint("NewApi")
	public static String getPath(final Context context, final Uri uri) {

	    final boolean isKitKat = Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT;

	    // DocumentProvider
	    if (isKitKat && DocumentsContract.isDocumentUri(context, uri)) {
	        // ExternalStorageProvider
	        if (isExternalStorageDocument(uri)) {
	            final String docId = DocumentsContract.getDocumentId(uri);
	            final String[] split = docId.split(":");
	            final String type = split[0];

	            if ("primary".equalsIgnoreCase(type)) {
	                return Environment.getExternalStorageDirectory() + "/" + split[1];
	            }

	            // TODO handle non-primary volumes
	        }
	        // DownloadsProvider
	        else if (isDownloadsDocument(uri)) {

	            final String id = DocumentsContract.getDocumentId(uri);
	            final Uri contentUri = ContentUris.withAppendedId(
	                    Uri.parse("content://downloads/public_downloads"), ParseUtil.parseLong(id, 0));
	            return getDataColumn(context, contentUri, null, null);
	        }
	        // MediaProvider
	        else if (isMediaDocument(uri)) {
	            final String docId = DocumentsContract.getDocumentId(uri);
	            final String[] split = docId.split(":");
	            final String type = split[0];

	            Uri contentUri = null;
	            if ("image".equals(type)) {
	                contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
	            } else if ("video".equals(type)) {
	                contentUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
	            } else if ("audio".equals(type)) {
	                contentUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
	            }

	            final String selection = "_id=?";
	            final String[] selectionArgs = new String[] {
	                    split[1]
	            };

	            return getDataColumn(context, contentUri, selection, selectionArgs);
	        }
	    }
	    // MediaStore (and general)
	    else if ("content".equalsIgnoreCase(uri.getScheme())) {

	        // Return the remote address
	        if (isGooglePhotosUri(uri))
	            return uri.getLastPathSegment();

	        return getDataColumn(context, uri, null, null);
	    }
	    // File
	    else if ("file".equalsIgnoreCase(uri.getScheme())) {
	        return uri.getPath();
	    }

	    return null;
	}
	/**
	 * Get the value of the data column for this Uri. This is useful for
	 * MediaStore Uris, and other file-based ContentProviders.
	 *
	 * @param context The context.
	 * @param uri The Uri to query.
	 * @param selection (Optional) Filter used in the query.
	 * @param selectionArgs (Optional) Selection arguments used in the query.
	 * @return The value of the _data column, which is typically a file path.
	 */
	public static String getDataColumn(Context context, Uri uri, String selection,
	        String[] selectionArgs) {

	    Cursor cursor = null;
	    final String column = "_data";
	    final String[] projection = {
	            column
	    };

	    try {
	        cursor = context.getContentResolver().query(uri, projection, selection, selectionArgs,
	                null);
	        if (cursor != null && cursor.moveToFirst()) {
	            final int index = cursor.getColumnIndexOrThrow(column);
	            return cursor.getString(index);
	        }
	    } finally {
	        if (cursor != null)
	            cursor.close();
	    }
	    return null;
	}


	/**
	 * @param uri The Uri to check.
	 * @return Whether the Uri authority is ExternalStorageProvider.
	 */
	public static boolean isExternalStorageDocument(Uri uri) {
	    return "com.android.externalstorage.documents".equals(uri.getAuthority());
	}

	/**
	 * @param uri The Uri to check.
	 * @return Whether the Uri authority is DownloadsProvider.
	 */
	public static boolean isDownloadsDocument(Uri uri) {
	    return "com.android.providers.downloads.documents".equals(uri.getAuthority());
	}

	/**
	 * @param uri The Uri to check.
	 * @return Whether the Uri authority is MediaProvider.
	 */
	public static boolean isMediaDocument(Uri uri) {
	    return "com.android.providers.media.documents".equals(uri.getAuthority());
	}

	/**
	 * @param uri The Uri to check.
	 * @return Whether the Uri authority is Google Photos.
	 */
	public static boolean isGooglePhotosUri(Uri uri) {
	    return "com.google.android.apps.photos.content".equals(uri.getAuthority());
	}
}
